package com.hykj.xxltest.utils;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.hykj.xxltest.config.Config;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class OSSUtil {
    private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);

    private static String ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";

//    private static String ACCESS_KEY_ID = "LTAIvoiUDMmHldmg";
//
//    private static String ACCESS_KEY_SECRET = "IcjYsy93f6H6nORd16n8ih3XGla7wf";

    public static final String BUCKETNAME = "wsctk";// laofoye.oss-cn-shanghai.aliyuncs.com

    public static final String FILE = "xiaocx/";

    public static final String FILE2 = "file/";

    // static {
    // ResourceBundle bundle =
    // PropertyResourceBundle.getBundle("properties.oss");
    // ENDPOINT = bundle.containsKey("endpoint") == false ? "" :
    // bundle.getString("endpoint");
    // ACCESS_KEY_ID = bundle.containsKey("accessKeyId") == false ? "" :
    // bundle.getString("accessKeyId");
    // ACCESS_KEY_SECRET = bundle.containsKey("accessKeySecret") == false ? "" :
    // bundle.getString("accessKeySecret");
    // }

    /**
     * 获取阿里云OSS客户端对象
     */
    public static final OSSClient getOSSClient() {
        return new OSSClient(ENDPOINT, Config.accessKeyId, Config.accessKeySecret);
    }

    /**
     * 新建Bucket --Bucket权限:私有
     *
     * @param bucketName bucket名称
     * @return true 新建Bucket成功
     */
    public static final boolean createBucket(OSSClient client, String bucketName) {
        Bucket bucket = client.createBucket(bucketName);
        return bucketName.equals(bucket.getName());
    }

    /**
     * 删除Bucket
     *
     * @param bucketName bucket名称
     */
    public static final void deleteBucket(OSSClient client, String bucketName) {
        client.deleteBucket(bucketName);
        logger.info("删除" + bucketName + "Bucket成功");
    }

    /**
     * 向阿里云的OSS存储中存储文件 --file也可以用InputStream替代
     *
     * @param client     OSS客户端
     *                   <p>
     *                   上传文件
     * @param bucketName bucket名称
     * @param diskName   上传文件的目录 --bucket下文件的路径
     * @return String 唯一MD5数字签名
     */
    public static final Map<String, String> uploadObject2OSS(OSSClient client, FileItem item, String bucketName,
                                                             String diskName) {
        Map<String, String> result = null;
        String resultStr = null;
        String url = null;
        InputStream is = null;
        try {
            is = item.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {

            String fileName = uploadFileName(item);
            Long fileSize = item.getSize();
            url = "http://" + bucketName + "." + ENDPOINT + "/" + diskName + fileName;

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

            PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);

            // 解析结果
            resultStr = putResult.getETag();
            result = new HashMap<String, String>();
            result.put("url", url);
            result.put("resultStr", resultStr);

        } catch (Exception e) {
            logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String uploadObject2OSS(OSSClient client, File file, String diskName, String bucketName,
                                          String fileFileName) {

        String fileName = uploadFileName(file, fileFileName);

        client.putObject(bucketName, diskName + fileName, file);

        String url = "http://" + bucketName + "." + ENDPOINT + "/" + diskName + fileName;

        return url;

    }

    public static String uploadBytes2OSS(OSSClient client, String diskName, String bucketName,
                                         ByteArrayInputStream bytes) {
        String fileName = uploadFileName(null, null);
        client.putObject(bucketName, diskName + fileName, bytes);

        String url = "http://" + bucketName + "." + ENDPOINT + "/" + diskName + fileName;
        return url;
    }

    public static String uploadBytes2OSS(OSSClient client, String diskName, String bucketName,
                                         ByteArrayInputStream bytes, String fileName2) {
        String fileName = uploadFileName(null, fileName2);
        client.putObject(bucketName, diskName + fileName, bytes);

        String url = "http://" + bucketName + "." + ENDPOINT + "/" + diskName + fileName;
        return url;
    }

    private static String uploadFileName(FileItem item) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-M-d mm:ss:SSS");
        Random random = new Random();
        String time = sdf.format(new Date());
        String time1 = time.replaceAll(" ", "-").replaceAll("-", "").replaceAll(":", "");
        int a = random.nextInt(90) + 10;
        String name = time1 + a;

        File tempFile = new File(item.getName());

        String fileName = name;
        return fileName;
    }

    private static String uploadFileName(File file, String fileFileName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-M-d mm:ss:SSS");
        Random random = new Random();
        String time = sdf.format(new Date());
        String time1 = time.replaceAll(" ", "-").replaceAll("-", "").replaceAll(":", "");
        int a = random.nextInt(90) + 10;
        String name = time1 + a;
        String fileName;
        if (fileFileName != null) {
            String prefix = fileFileName.substring(fileFileName.lastIndexOf("."));
            fileName = name + prefix;
            logger.info(fileName);
        } else {
            fileName = name + ".png";
        }

        // File tempFile = new File(item.getName());


        return fileName;
    }

    /**
     * 根据key获取OSS服务器上的文件输入流
     *
     * @param client     OSS客户端
     * @param bucketName bucket名称
     * @param diskName   文件路径
     * @param key        Bucket下的文件的路径名+文件名
     */
    public static final InputStream getOSS2InputStream(OSSClient client, String bucketName, String diskName, String key) {
        OSSObject ossObj = client.getObject(bucketName, diskName + key);
        return ossObj.getObjectContent();
    }

    /**
     * 根据key删除OSS服务器上的文件
     *
     * @param client     OSS客户端
     * @param bucketName bucket名称
     * @param diskName   文件路径
     * @param key        Bucket下的文件的路径名+文件名
     */
    public static void deleteFile(OSSClient client, String bucketName, String diskName, String key) {
        client.deleteObject(bucketName, diskName + key);
        logger.info("删除" + bucketName + "下的文件" + diskName + key + "成功");
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static final String getContentType(String fileName) {
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if ("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)
                || "png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if ("html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if ("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if ("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        return "text/html";
    }
}
